#include<stdio.h>
#include<malloc.h>
#include<stdbool.h>

struct node {
	struct node *next;
	int val;
};

#define BUCKETS 16

int hash(int val)
{
	return val % BUCKETS;
}

struct node *hasht[BUCKETS];

bool exists(struct node *hasht[], int val)
{
	int bucket = hash(val);
	struct node *p;

	p = hasht[bucket];
	while (p) {
		if (p->val == val)
			return true;
		p = p->next;
	}

	return false;
}

int insert(struct node *hasht[], int val)
{
	int bucket = hash(val);
	struct node *p;

	if (exists(hasht, val)) {
		printf("%d already exists \n", val);
		return -1;

	}

	p = malloc(sizeof(*p));
	p->val = val;
	p->next = hasht[bucket];
	hasht[bucket] = p;

	return 0;
}

void print_chain(struct node *head)
{
	struct node *p = head;

	while (p) {
		printf("%d ", p->val);
		p = p->next;
	}
}

void print_hasht(struct node *hasht[])
{
	int i;

	for (i = 0; i < BUCKETS; i++) {
		printf("%d: ", i);
		print_chain(hasht[i]);
		printf("\n");
	}
}

int main(void)
{

	insert(hasht, 301);
	insert(hasht, 78);
	insert(hasht, 5);
	insert(hasht, 89);
	insert(hasht, 56);
	insert(hasht, 44);
	insert(hasht, 1000);
	insert(hasht, 45);
	insert(hasht, 666);
	insert(hasht, 4545);
	insert(hasht, 555);
	insert(hasht, 16);
	insert(hasht, 32);
	insert(hasht, 48);
	insert(hasht, 64);
	insert(hasht, 64);
	insert(hasht, 64);

	if (exists(hasht, 48))
		printf("48 exists\n");
	else
		printf("48 does not exists \n");

	print_hasht(hasht);

	return 0;
}
